from odoo import api, models, fields, _
from odoo.tools.float_utils import float_compare, float_round
from odoo.exceptions import ValidationError
from datetime import datetime


class QualityCheck(models.Model):
    _inherit = 'quality.check'

    def _default_s_readonly(self):
        return self._context.get('sb_expired_quality', False)

    s_product_qty = fields.Float(string='Product Qty', digits='Product Unit of Measure')
    s_good_product_qty = fields.Float(string='Good Qty', digits='Product Unit of Measure')
    s_scrap_qty = fields.Float(string='Scrap Qty', digits='Product Unit of Measure')
    s_readonly = fields.Boolean(default=_default_s_readonly)
    s_check_type = fields.Selection([
        ('expired_quality', 'Expired Quality'),
        ('iqc', 'IQC')
    ], string='Quality Check Type')
    s_expiration_date = fields.Datetime(string='Expiration Date')

    def do_pass(self):
        super().do_pass()
        for rec in self:
            if rec.quality_state == 'fail':
                raise ValidationError(_('Quality inspection completed, unable to perform this operation!'))

            rec.s_good_product_qty = rec.s_product_qty
            rec.s_scrap_qty = 0
            # 临期质检
            if rec.s_check_type == 'expired_quality' and rec.picking_id and rec.picking_id.picking_type_id.barcode == 'WTT-EQ':
                rounding = rec.product_id.uom_id.rounding
                contrast = float_compare(rec.s_product_qty, rec.s_good_product_qty+rec.s_scrap_qty, precision_rounding=rounding)
                if contrast:
                    raise ValidationError(_('The total number of good products plus scrapped products is not equal. Please re-enter the quantity!'))
                rec.create_picking_good(qty=rec.s_good_product_qty)
                if rec.s_scrap_qty:
                    rec.create_picking_scrap(qty=rec.s_scrap_qty)
                lot = rec.lot_id
                time_delta = rec.s_expiration_date - lot.expiration_date
                lot.update({
                    'use_date': lot._origin.use_date and lot._origin.use_date + time_delta,
                    'removal_date': lot._origin.removal_date and lot._origin.removal_date + time_delta,
                    'alert_date': lot._origin.alert_date and lot._origin.alert_date + time_delta,
                    'expiration_date': rec.s_expiration_date,
                })

            if rec.s_check_type == 'iqc' and rec.quality_state == 'pass':
                message = _('Product: %s, Lot: %s, warehousing entry: %s, The quality inspection has been passed. Please store it in the warehouse as soon as possible',
                            rec.product_id.name, rec.lot_id.name or rec.lot_name, rec.name)
                # groups="stock.group_stock_manager,stock.group_stock_user"
                self.env['mail.message'].sudo().post_message_to_group_user('sb_base.group_sb_stock_message_receive', message)

    def do_fail(self):
        if self.quality_state == 'pass':
            raise ValidationError(_('The quality inspection has been passed and cannot be revoked!'))
        self.s_scrap_qty = self.s_product_qty
        self.s_good_product_qty = 0
        if self.s_check_type == 'expired_quality':
            # pickings = self.env['stock.picking'].search([('origin', '=', self.name)])
            # done_picking = pickings.filtered(lambda x: x.state=='done')
            # if done_picking:
            #     raise ValidationError(_('质检入库调拨已完成，无法取消。'))
            # for p in pickings:
            #     p.action_cancel()
            self.create_picking_scrap(qty=self.s_scrap_qty)
        elif self.s_check_type == 'iqc' and self.picking_id.state == 'done':
            raise ValidationError(_('The raw materials have been received and cannot be cancelled.'))
        return super().do_fail()

    def create_picking_good(self, qty):
        """临期质检->正常库位"""
        picking_type = self.picking_id.picking_type_id
        # picking_type = self.env['stock.picking.type'].search([('barcode', '=', 'WTT-INTERNAL')])
        location_dest_id = self.picking_id.location_id
        picking_vals = {
            'name': picking_type.sequence_id.next_by_id(),
            'origin': self.name,
            'picking_type_id': picking_type.id,
            'location_id': self.env.ref('sb_quality_check.location_quality_check').id,
            'location_dest_id': location_dest_id.id,
            'scheduled_date': fields.Datetime.now(),
            'move_ids': [(0, 0, self._get_move_vals(picking_type, qty, location_dest_id))],
        }
        picking = self.env['stock.picking'].create(picking_vals)
        return picking

    def create_picking_scrap(self, qty):
        """临期质检->报废位置"""
        # picking_type = self.env.ref('sb_quality_check.picking_type_expired_scrap_quality')
        # 系统报废类型
        picking_type = self.env['stock.picking.type'].browse(16)
        # location_dest_id = self.env.ref('sb_quality_check.location_quality_check_scrap')
        location_dest_id = self.env['stock.location'].sudo().search([('scrap_location', '=', True)], limit=1)
        if not location_dest_id:
            location_dest_id = self.env['stock.location'].sudo().browse(16)

        picking_vals = {
            'name': picking_type.sequence_id.next_by_id(),
            'origin': self.name,
            'picking_type_id': picking_type.id,
            'location_id': self.env.ref('sb_quality_check.location_quality_check').id,
            'location_dest_id': location_dest_id.id,
            'scheduled_date': fields.Datetime.now(),
            'move_ids': [(0, 0, self._get_move_vals(picking_type, qty, location_dest_id))],
        }
        picking = self.env['stock.picking'].create(picking_vals)
        return picking

    def _get_move_vals(self, picking_type, qty, location_dest_id):
        return {
            'company_id': self.env.user.company_id.id,
            'date': datetime.now(),
            'location_id': picking_type.default_location_src_id.id,
            'location_dest_id': picking_type.default_location_dest_id.id,
            'product_id': self.product_id.id,
            'name': self.product_id.display_name,
            'procure_method': 'make_to_stock',
            'product_uom': self.lot_id.product_uom_id.id,
            'product_uom_qty': qty,
            'lot_ids': [(0, 0, [self.lot_id.id])],
            'move_line_ids': [(0, 0, {
                'product_id': self.product_id.id,
                'lot_id': self.lot_id.id,
                'quantity': qty,
                'location_id': self.env.ref('sb_quality_check.location_quality_check').id,
                'location_dest_id': location_dest_id.id,
            })]
        }
